package io.terminus.lego.shinda.web.security.phone.filter

import io.terminus.lego.shinda.web.security.phone.token.SmsLoginAuthenticationToken
import org.springframework.http.HttpMethod
import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter
import org.springframework.security.web.util.matcher.AntPathRequestMatcher
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 短信验证码登录
 * @author wangmeng
 * @date 2018/4/19
 */

class SMSCodeAuthenticationProcessingFilter : AbstractAuthenticationProcessingFilter {
    var PARAMTER_KEY_PHONE = "phoneNumber"
    var PARAMTER_KEY_CODE = "verificationCode"

    constructor() : super(AntPathRequestMatcher("/login-phone", HttpMethod.POST.name))


    override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication {
        var phone = request.getParameter(PARAMTER_KEY_PHONE)
        var code = request.getParameter(PARAMTER_KEY_CODE)
        if (phone.isNullOrEmpty()) {
            phone = ""
        }
        if (code.isNullOrEmpty()) {
            code = ""
        }
        phone = phone.trim()
        val authRequest = SmsLoginAuthenticationToken(phone, code)
        // Allow subclasses to set the "details" property
        setDetails(request, authRequest)

        return this.authenticationManager.authenticate(authRequest)
    }

    private fun setDetails(request: HttpServletRequest, authRequest: SmsLoginAuthenticationToken) {
        authRequest.details = authenticationDetailsSource.buildDetails(request)
    }

}